package link.anyauto.weclass.demos.actionbar;

import android.app.Activity;
import android.databinding.ObservableField;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.widget.SearchView;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;

import link.anyauto.weclass.R;
import link.anyauto.weclass.base.BaseVMAdapter;
import link.anyauto.weclass.util.ToastUtil;

/**
 * Created by Administrator on 2017/2/22.
 */

public class ActionBarVM extends BaseVMAdapter {

    public ObservableField<String> query = new ObservableField<>();
    boolean searchShow = false;

    public ActionBarVM(final Activity activity) {
        setActivity(activity);
        title(R.string.app_bar_demo);
        subTitle(R.string.app_bar_demo_subtitle);
    }

    @Override
    public boolean createOptionsMenu(MenuInflater inflater, Menu menu) {
        inflater.inflate(R.menu.app_bar_menu, menu);
        return true;
    }

    @Override
    public boolean prepareOptionsMenu(Menu menu) {
        for (int i=0; i<menu.size(); i++) {
            MenuItem item = menu.getItem(i);
            item.setVisible(true);
            item.setEnabled(true);
        }
        return !searchShow;
    }

    @Override
    public void optionsMenuClosed(Menu menu) {
        for (int i=0; i<menu.size(); i++) {
            MenuItem item = menu.getItem(i);
            item.setVisible(true);
            item.setEnabled(true);
        }
        super.optionsMenuClosed(menu);
    }

    @Override
    public boolean optionsItemSelected(MenuItem item) {
        ToastUtil.toast(item.getTitle().toString());
        if(item.getItemId() == R.id.action_search) {
            final SearchView sv = (SearchView) MenuItemCompat.getActionView(item);
            sv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
                @Override
                public boolean onQueryTextSubmit(String s) {
                    query.set(s);
                    return true;
                }

                @Override
                public boolean onQueryTextChange(String s) {
                    query.set(s);
                    return true;
                }
            });
            sv.setOnQueryTextFocusChangeListener(new View.OnFocusChangeListener() {
                @Override
                public void onFocusChange(View view, boolean b) {
                    query.set(sv.getQuery().toString());
                    searchShow = b;
                }
            });
        }
        return super.optionsItemSelected(item);
    }
}
